<?php
include_once '../Model/Execute.php';
function getDetailById($idOrden) {
    $array_prop = parse_ini_file('DataAcces.properties');

    $enlace = mysqli_connect($array_prop['servidor'], $array_prop['usuario'], $array_prop['contra'], $array_prop['base']);

    /* verificar la conexión */
    if (mysqli_connect_errno()) {
        printf("Conexión fallida: %s\n", mysqli_connect_error());
        exit();
    }

    $consulta = "SELECT o.ordenDetail,o.cantidad, o.descripcion, o.proveedor, o.precioUnitario, o.discount,"
            . "ROUND((o.cantidad*o.precioUnitario) - (o.cantidad*o.precioUnitario*(o.discount/100)),2) total, ord.creationUser "
            . "FROM u225435723_orden.ORDEN_DETAIL o INNER JOIN u225435723_orden.ORDEN ord ON (ord.idOrden = o.idOrden) WHERE o.idOrden = ".$idOrden." ORDER BY o.ordenDetail DESC";

    if ($resultado = mysqli_query($enlace, $consulta)) {
        /* obtener array asociativo */
        while ($row = mysqli_fetch_assoc($resultado)) {
            $results[] = $row;
        }
        /* liberar el conjunto de resultados */
        mysqli_free_result($resultado);
    }

    /* cerrar la conexión */
    mysqli_close($enlace);
    if (isset($results))
        return $results;
}

function insertarOrdenDetail($params,$user,$idOrden) {
    $array_prop = parse_ini_file('DataAcces.properties');
    $con = mysqli_connect($array_prop['servidor'], $array_prop['usuario'], $array_prop['contra'], $array_prop['base']);
    if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
    try{
        mysqli_begin_transaction($con);
        for($i=0;$i<sizeof($params);$i++){ mysqli_query($con, $params[$i]); }
        // Si logra insertar, se cambia el estado a pending to aprove coordinator, un send automatico
        $update = "UPDATE `u225435723_orden`.`ORDEN` SET  `step`='PAC', `modificationDate` = NOW(), `modificationUser` = '"
                . $user . "' WHERE `idOrden` = ". $idOrden;
        mysqli_query($con, $update);
        // Si logra insertar, adjunto los archios correspondientes
        $update = "UPDATE `u225435723_orden`.`ATTACHED_FILE` SET  `idOrden`=" . $idOrden . " WHERE `idOrden` IS NULL AND `creationUser` = '" . $user ."'";
        mysqli_query($con, $update);
        mysqli_commit($con);
        mysqli_close($con);
        sendEstatusNotificationMail($idOrden);
        return sizeof($params);
    } catch (Exception $e){
        mysqli_rollback($con);
        mysqli_close($con);
        return 0;
    }
}

function actualizarOrdenDetail($params,$idOrdenDet,$idOrden){
    $array_prop = parse_ini_file('DataAcces.properties');
    $con = mysqli_connect($array_prop['servidor'], $array_prop['usuario'], $array_prop['contra'], $array_prop['base']);
    // Check connection
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    if($idOrdenDet==0){
        $update = "INSERT INTO `u225435723_orden`.`ORDEN_DETAIL` "
                        . "(`idOrden`,`cantidad`,`descripcion`,`proveedor`,"
                        . "`precioUnitario`,`discount`,`tipoOrdenCode`) VALUES ("
                        .$idOrden .",".$params[0] . ",'".$params[1] ."','"
                        .$params[2] ."',".$params[3] . ",".$params[4] . ",". "'COM')";
    }else {
        $update = "UPDATE u225435723_orden.ORDEN_DETAIL SET cantidad = ".$params[0]. ", descripcion ='". $params[1]
                . "', proveedor = '".$params[2]."', precioUnitario = ".$params[3].", discount = ".$params[4]
                . " WHERE ordenDetail = ".$idOrdenDet;
    }

    $result = mysqli_query($con, $update);

    mysqli_commit($con);

    mysqli_close($con);
    return $result;
}

function eliminarOrdenDetail($ordenDetail){
    $array_prop = parse_ini_file('DataAcces.properties');
    $con = mysqli_connect($array_prop['servidor'], $array_prop['usuario'], $array_prop['contra'], $array_prop['base']);
    // Check connection
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    $delete = "DELETE FROM `u225435723_orden`.`ORDEN_DETAIL` WHERE ordenDetail = " . $ordenDetail;
    $result = mysqli_query($con, $delete);
    mysqli_commit($con);

    mysqli_close($con);
    return $result;
}